import { cn, getFileName } from '@/lib/utils';
import { Button } from './ui/button';
import { useSettingsStore } from '@/store';
import appConfig from '@/app.config';
import { toast } from 'sonner';
import { Mutate, StoreApi, UseBoundStore } from 'zustand';

type Props = {
  children?: React.ReactNode;
  className?: string;
  store?: UseBoundStore<Mutate<StoreApi<any>, any>>;
  suggestedName?: string;
};

export default function SettingsPersisted({
  children,
  className,
  store,
  suggestedName,
  ...props
}: Props) {
  const useStore = store || useSettingsStore;
  async function exportSettings() {
    const settings = useStore.getState();
    const settingsString = JSON.stringify(settings);
    const settingsFileHandle = await window.showSaveFilePicker({
      id: 'settings',
      suggestedName: suggestedName || appConfig.settingsFilename,
    });
    const loadingId = toast.loading('正在导出配置');
    try {
      const writable = await settingsFileHandle.createWritable();
      await writable.write(settingsString);
      await writable.close();
      toast.success(`成功导出配置`);
      toast.dismiss(loadingId);
    } catch (error) {
      toast.error(`导出配置失败 ${(error as Error).message}`);
      toast.dismiss(loadingId);
    }
  }

  async function importSettings() {
    const settingsFileHandle = await window.showOpenFilePicker({
      id: 'settings',
    });
    const loadingId = toast.loading('正在导入配置');
    try {
      const settingsFile = await settingsFileHandle[0].getFile();
      const settingsString = await settingsFile.text();
      useStore.setState(JSON.parse(settingsString));
      toast.success(`成功导入配置`);
      toast.dismiss(loadingId);
    } catch (error) {
      toast.error(`导入配置失败 ${(error as Error).message}`);
      toast.dismiss(loadingId);
    }
  }

  return (
    <div className={cn(className, 'felx items-center')} {...props}>
      <Button onClick={exportSettings} size="sm" className="mr-3">
        导出设置
      </Button>
      <Button onClick={importSettings} size="sm" className="">
        导入设置
      </Button>
    </div>
  );
}
